package com.dreamoo.service.ai;

import com.dreamoo.common.enums.FileStorageEnum;
import com.dreamoo.common.exception.BusinessException;
import com.dreamoo.service.factory.FileStorageFactory;
import com.dreamoo.service.strategy.image.FileStoragStrategy;
import dev.langchain4j.data.image.Image;
import dev.langchain4j.model.image.ImageModel;
import dev.langchain4j.model.output.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.Base64;
import java.util.UUID;

/**
 * @author 山顶洞人郑某
 * @className ImageAnalyst.java 图片分析和生成
 * @date 2025 05 14
 */
@Component
@Slf4j
public class ImageAnalyst {

    @Autowired
    @Qualifier("openAiImageModel")
    private ImageModel imageModel;

    @Autowired
    private FileStorageFactory fileStorageFactory;

    /**
     * 生成梦境图片并返回图片地址
     *
     * @param dreamContent 梦境描述
     * @return 图片URL地址
     */
    public String createDreamImage(String dreamContent) {
        log.info("开始生成梦境图片, 梦境描述: {}", dreamContent);

        Response<Image> imageResponse = imageModel.generate(dreamContent);
        log.info("生成的梦境信息{}",imageResponse);
        //获取存储策略
        FileStoragStrategy ossStorage = fileStorageFactory.getFileStoragStrategy(FileStorageEnum.OSS);
        String mimeType = imageResponse.content().mimeType();
        String url = ossStorage.saveFile(imageResponse.content(),mimeType);
        //将路径存储到本地数据库
        log.info("梦境图片生成成功, 图片地址: {}", url);

        return url;
    }

}